package net.qiyuesuo.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.qiyuesuo.service.FileService;
import net.qiyuesuo.service.impl.FileServiceImpl;

/**
 * 上传文件接口
 * @author Administrator
 *
 */
@MultipartConfig
public class UploadFileServlet extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	private FileService fileService = new FileServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//说明输入的请求信息采用UTF-8编码方式
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		//获取上传的文件
		Part part = request.getPart("file");
		String headerInfo = part.getHeader("content-disposition");
		String fileName = headerInfo.substring(headerInfo.lastIndexOf("=") + 2, headerInfo.length() - 1);
		//获得存储上传文件的文件夹路径
		Path path = Paths.get("C:\\Users\\Administrator\\AppData\\Local\\Temp\\"+fileName);
		part.write(fileName);
		File file = path.toFile();
		fileService.saveFile(file);
		out.write("成功上传文件:"+fileName);
		logger.info("成功存储文件：" + fileName);
		//删除临时文件
	    file.delete();
	}
	
}